<?php
namespace Asset\Controller;
use Common\Controller\AdminbaseController;
use Library\Wx;
class QrcodeController extends AdminbaseController {
	protected $qrcode_list_model;
	function _initialize() {
		parent::_initialize();
		$this->qrcode_list_model = D("QrcodeList");
	}

    private function qtype() {
		$qtype =
			array(
	            array('id' => '0','name'=>'临时二维码'),
	            array('id' => '1','name'=>'永久二维码'),
	        );
		return $qtype;
    }
    function index() {
		$count=$this->qrcode_list_model->count();
		$page = $this->page($count, 50);
		$lists=$this->qrcode_list_model
		->limit($page->firstRow . ',' . $page->listRows)
		->order("id DESC")->select();
		if($lists){
			foreach($lists as$luser){
				$uid[] =$luser['userid'];
			}
			$users=M("Users")->field("id,user_login")->where(array('id'=>array('in',$uid)))->select();
			$this->assign("users", $users);
		}
		$this->assign("type", $this->qtype());
    	$this->assign('page', $page->show('Admin'));
		$this->assign("lists", $lists);
		$this->assign("count", $count);
		$this->display();
	}

    function add() {
		$this->assign("type", $this->qtype());
		$this->display();
    }
    function add_post() {
		if (IS_POST) {
			if(!I('post.name')){
				$this->error('请输入用途名称');
			}
			$_POST['userid'] = get_current_admin_id();
			$qtype =I('post.qtype');
			if($qtype){
				$_POST['expire'] = 0;
			}
			$qid=$this->qrcode_list_model->add($_POST);
			if($qid){
				$code = \Library\Wx::getQRCode($qid,$qtype,I('post.expire'));
				$url = \Library\Wx::getQRUrl($code['ticket']);
				$date['codeurl'] = $url;
				$this->qrcode_list_model->where(array('id'=>$qid))->save($date);
				$this->success("添加成功！",U('Qrcode/index'));
			}else{
				$this->error("添加失败！");
			}
		}
    }
    function edit() {
		$id = intval(I("get.id"));
		$list = $this->qrcode_list_model->where("id=$id")->find();
		$this->assign("type", $this->qtype());
		$this->assign("list", $list);
		$this->display();
    }
    function edit_post() {
		if (IS_POST) {
			$id = intval(I("get.id"));
			if(!I('post.name')){
				$this->error('请输入用途名称');
			}
			$_POST['userid'] = get_current_admin_id();
			if($this->qrcode_list_model->where(array('id'=>$id))->save($_POST)){
				$this->success("修改成功！",U('Qrcode/index'));
			}else{
				$this->error("修改失败！");
			}
		}
    }
    function delete() {
    	if (I("get.id")) {
    		if ($this->qrcode_list_model->where(array('id'=>I("get.id")))->delete()) {
    			$this->success("删除成功！");
    		} else {
    			$this->error('删除失败！');
    		}
    	} else {
			$this->error($this->qrcode_list_model->getError());
    	}
    }
}
